<template>
  <el-cascader
    v-model="selectedValue"
    :options="treeData"
    :props="cascaderProps"
    clearable
    @change="handleNodeChange"
    style="width: 100%"
  />
</template>

<script>
import { getAmmeterTree } from "@/api/mes/bm/ammeter";

export default {
  name: "RegionAmmeterSelect",
  props: {
    value: {
      type: [Array, String, Number],
      default: null
    },
    // 是否严格的选择模式
    checkStrictly: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      treeData: [],
      selectedValue: this.value
    };
  },
  computed: {
    cascaderProps() {
      return {
        checkStrictly: this.checkStrictly,
        emitPath: true,
        expandTrigger: 'hover',
        value: 'id',
        label: 'name',
        children: 'children'
      };
    }
  },
  watch: {
    value(newVal) {
      this.selectedValue = newVal;
    }
  },
  created() {
    this.getTreeData();
  },
  methods: {
    getTreeData() {
      getAmmeterTree().then(response => {
        if (response.code === 200 && response.data) {
          this.treeData = this.formatTreeData(response.data);
        }
      });
    },
    formatTreeData(data) {
      if (!data || data.length === 0) {
        return [];
      }

      const rootName = data[0]?.bmMonitor?.psectorName || "北化浩绅";
      const root = {
        id: '0',
        name: rootName,
        type: 'master',
        children: []
      };

      data.forEach(item => {
        if (item.bmMonitor) {
          const monitorNode = {
            id: item.bmMonitor.id,
            name: item.bmMonitor.name,
            type: 'slave',
            children: []
          };

          if (item.bmAmmeterList && Array.isArray(item.bmAmmeterList)) {
            monitorNode.children = item.bmAmmeterList.map(ammeter => ({
              id: ammeter.id,
              name: ammeter.name,
              type: 'ammeter',
              monitorId: ammeter.monitorId
            }));
          }

          root.children.push(monitorNode);
        }
      });

      return [root];
    },
    handleNodeChange(value) {
      this.$emit('input', value);
      if (!value || value.length === 0) {
        this.$emit('change', { id: null, type: null });
      } else {
        const selectedValue = value[value.length - 1];
        const selectedNode = this.findNodeById(this.treeData, selectedValue);
        if (selectedNode) {
          this.$emit('change', {
            id: selectedValue,
            type: selectedNode.type
          });
        }
      }
    },
    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) {
          return node;
        }
        if (node.children) {
          const found = this.findNodeById(node.children, id);
          if (found) {
            return found;
          }
        }
      }
      return null;
    }
  }
};
</script> 